package top.jnaw.jee.utils.quartz;


import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import com.jfinal.plugin.activerecord.Db;
import java.util.List;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import top.jnaw.jee.platform.model.JobManage;
import top.jnaw.jee.utils.Log;

/**
 * Copyright (C) 2018 版权所有。 <p> 文件名： 文件功能描述：
 *
 * @author lc  2018/8/27 16:14 创建内容： <p> <p> 修改标识： 修改原因：
 */
public class QuartzManager {

  private Logger log = LogManager.getLogger(QuartzManager.class);

  private Scheduler scheduler = null;

  public QuartzManager() {
    try {
      scheduler = new StdSchedulerFactory().getScheduler();
      Log.i("初始化调度器 ");
    } catch (SchedulerException ex) {
      Log.e("初始化调度器=> [失败]:" + ex.getLocalizedMessage());
    }
  }

  //测试
  public static void main(String[] args) throws InterruptedException {
    QuartzManager qm = new QuartzManager();
    String name = "重置商户积分";
    String group = "shop";
    String cronExpression = "*/3 * * * * ?";
    String className = "top.jnaw.jee.utils.quartz.ResetShopScore";
    Class<? extends Job> jobClazz = null;
    try {
      jobClazz = Class.forName(className).asSubclass(Job.class);
    } catch (Exception e) {
      System.out.println(className + "没有继承job,e==" + e);
    }
    if (jobClazz == null) {
      System.exit(0);
    }
//    qm.addJob(name, group, jobClazz, cronExpression);
    qm.start();
//    Thread.sleep(7000);
    qm.removeJob(name, group);
//    Thread.sleep(3000);
//    String name2 = "DynamicJobName2";
//    String group2 = "DynamicJobGroup2";
//    String cronExpression2 = "*/3 * * * * ?";
////    qm.addJob(name2, group2, NoJournalJob.class, cronExpression2);
//    Thread.sleep(9000);
    qm.shutdown();
  }

  //初始化启动任务
  public void initJob() {
    String select = Db.getSql("job_manage-list");
    String except = Db.getSql("job_manage-list-except");
    String sql = select + except + "   WHERE  is_enabled = 'Y'";
    List<JobManage> jobs = JobManage.dao.find(sql);

    for (JobManage job : jobs) {
      String className = job.getClazz();
      Class<? extends Job> jobClazz = null;
      try {
        jobClazz = Class.forName(className).asSubclass(Job.class);
      } catch (Exception e) {
        System.out.println(className + "没有继承job,e==" + e);
        Log.e(className + "没有继承job,e==" + e);
        continue;
      }
      String name = job.getName();
      String group = job.getType();
      String cronExpression = job.getCronExpression();

      Log.w("add job: " + className + ", " + cronExpression);
      this.addJob(name, group, jobClazz, cronExpression);

    }
    this.start();

  }

  //添加任务
  public void addJob(String name, String group, Class<? extends Job> clazz,
      String cronExpression) {
    try {
      // 构造任务
      JobDetail job = newJob(clazz).withIdentity(name, group).build();
      // 构造任务触发器
      Trigger trg = newTrigger().withIdentity(name, group)
          .withSchedule(cronSchedule(cronExpression)).build();
      // 将作业添加到调度器
      scheduler.scheduleJob(job, trg);
      Log.i("创建作业=> [作业名称：" + name + " 作业组：" + group + "] ");
      System.out.println("创建作业=> [作业名称：" + name + " 作业组：" + group + "] ");
    } catch (SchedulerException e) {
      e.printStackTrace();
      Log.e("创建作业=> [作业名称：" + name + " 作业组：" + group + "]=> [失败]");
    }
  }

  //移除任务
  public void removeJob(String name, String group) {
    try {
      TriggerKey tk = TriggerKey.triggerKey(name, group);
      scheduler.pauseTrigger(tk);// 停止触发器
      scheduler.unscheduleJob(tk);// 移除触发器
      JobKey jobKey = JobKey.jobKey(name, group);
      scheduler.deleteJob(jobKey);// 删除作业
      Log.i("删除作业=> [作业名称：" + name + " 作业组：" + group + "] ");
      System.out.println("删除作业=> [作业名称：" + name + " 作业组：" + group + "] ");
    } catch (SchedulerException e) {
      e.printStackTrace();
      Log.e("删除作业=> [作业名称：" + name + " 作业组：" + group + "]=> [失败]");
    }
  }

  public void start() {
    try {
      scheduler.start();
      Log.i("启动调度器 ");
    } catch (SchedulerException e) {
      e.printStackTrace();
      Log.e("启动调度器=> [失败]");
    }
  }

  public void shutdown() {
    try {
      scheduler.shutdown();
      Log.i("停止调度器 ");
    } catch (SchedulerException e) {
      e.printStackTrace();
      Log.e("停止调度器=> [失败]");
    }
  }
}
